<template>
  <view class="bg-white h-screen flex flex-col">
    <!-- 顶部导航栏 -->
    <view class="px-6 pt-12 pb-4 flex items-center justify-between border-b border-gray-100">
      <view class="flex items-center">
        <view class="text-blue-500 mr-3" @click="goBack">
          <text class="fas fa-chevron-left"></text>
        </view>
        <view>
          <text class="text-xl font-bold">播放列表</text>
        </view>
      </view>
      <view class="flex items-center space-x-4">
        <view class="text-gray-600 hover-text-gray-800" @click="togglePlayMode">
          <text class="fas" :class="isRandomMode ? 'fa-random' : 'fa-redo-alt'" style="font-size: 36rpx;"></text>
        </view>
        <view class="text-red-500 hover-text-red-600" @click="confirmClearPlaylist">
          <text class="fas fa-trash-alt" style="font-size: 36rpx;"></text>
        </view>
      </view>
    </view>

    <!-- 主要内容区域 -->
    <view class="flex-1 px-6 py-4 overflow-auto">
      <!-- 加载状态 -->
      <view v-if="loading" class="py-8 flex flex-col items-center justify-center">
        <view class="loading-spinner mb-3"></view>
        <text class="text-gray-500">加载中...</text>
      </view>

      <!-- 空状态 -->
      <view v-else-if="playlist.patterns.length === 0" class="flex flex-col items-center justify-center h-64">
        <view class="w-24 h-24 bg-gray-100 rounded-full flex items-center justify-center mb-4">
          <text class="fas fa-music text-3xl text-gray-400"></text>
        </view>
        <text class="text-gray-500">播放列表为空</text>
        <navigator url="/pages/explore/index" open-type="switchTab" class="mt-4 text-blue-500 font-medium">去添加图案</navigator>
      </view>

      <!-- 播放列表项目 -->
      <view v-else class="space-y-3">
                  <view
            v-for="(item, index) in playlist.patterns"
            :key="item.pattern_id"
            class="rounded-xl p-4 flex items-center border playlist-item"
            :class="item.is_playing ? 'bg-blue-50 border-blue-100' : 'bg-white border-gray-100'"
            draggable="true"
            @dragstart="dragStart($event, index)"
            @dragend="dragEnd"
            @dragover.prevent
            @drop="drop($event, index)"
          >
          <view class="w-12 h-12 bg-gray-200 rounded-full flex items-center justify-center mr-4">
            <text class="fas" :class="getPatternIcon(item.pattern?.category)" style="font-size: 36rpx; color: #9ca3af;"></text>
          </view>
          <view class="flex-1">
            <text class="font-medium" :class="item.is_playing ? 'text-blue-600' : ''">{{ item.pattern?.pattern_name || '未知图案' }}</text>
            <text class="text-xs text-gray-500 block">{{ formatDuration(item.pattern?.duration) }}</text>
          </view>
          <view class="flex items-center space-x-2">
            <text v-if="item.is_playing" class="text-xs text-blue-500 bg-blue-100 px-2 py-1 rounded-full">播放中</text>
            <view class="text-gray-400 hover-text-gray-600 cursor-move pl-2 pr-1">
              <text class="fas fa-grip-vertical"></text>
            </view>
            <view class="text-gray-400 hover-text-gray-600 pl-1 pr-2" @click.stop="removePattern(item.pattern_id)">
              <text class="fas fa-times"></text>
            </view>
          </view>
        </view>
      </view>
    </view>
  </view>
</template>

<script>
import { playlistApi, deviceApi } from '@/api/index.js'

export default {
  data() {
    return {
      loading: false,
      playlist: {
        patterns: [],
        current_index: 0,
        play_mode: 0,
        auto_play: true
      },
      isRandomMode: true,
      deviceId: '',
      draggedItem: null,
      draggedIndex: -1
    }
  },
  
  onLoad(options) {
    this.deviceId = options.deviceId
    if (!this.deviceId) {
      uni.showToast({
        title: '设备ID不能为空',
        icon: 'none'
      })
      setTimeout(() => {
        uni.navigateBack()
      }, 1500)
      return
    }
    this.loadPlaylist()
  },
  
  onShow() {
    if (this.deviceId) {
      this.loadPlaylist()
    }
  },
  
  methods: {
    async loadPlaylist() {
      this.loading = true
      try {
        const result = await playlistApi.getPlaylists(this.deviceId)
        if (result && result.errCode === 0) {
          this.playlist = result.data || { patterns: [], current_index: 0, play_mode: 0, auto_play: true }
          // 设置播放模式
          this.isRandomMode = this.playlist.play_mode === 1
        } else {
          uni.showToast({
            title: result?.errMsg || '获取播放列表失败',
            icon: 'none'
          })
        }
      } catch (error) {
        console.error('加载播放列表失败:', error)
        uni.showToast({
          title: '网络错误，请重试',
          icon: 'none'
        })
      } finally {
        this.loading = false
      }
    },
    
    goBack() {
      uni.navigateBack()
    },
    
    // 切换播放模式
    async togglePlayMode() {
      this.isRandomMode = !this.isRandomMode
      const playMode = this.isRandomMode ? 1 : 0
      
      try {
        const result = await deviceApi.controlDevice(this.deviceId, {
          action: 'setPlayMode',
          playMode: playMode
        })
        
        if (result && result.errCode === 0) {
          this.playlist.play_mode = playMode
          uni.showToast({
            title: this.isRandomMode ? '已切换为随机播放' : '已切换为顺序播放',
            icon: 'none'
          })
        } else {
          uni.showToast({
            title: result?.errMsg || '设置播放模式失败',
            icon: 'none'
          })
        }
      } catch (error) {
        console.error('设置播放模式失败:', error)
        uni.showToast({
          title: '网络错误，请重试',
          icon: 'none'
        })
      }
    },
    
    // 确认清空播放列表
    confirmClearPlaylist() {
      uni.showModal({
        title: '清空播放列表',
        content: '确定要清空播放列表吗？此操作不可恢复。',
        confirmColor: '#ef4444',
        success: async (res) => {
          if (res.confirm) {
            await this.clearPlaylist()
          }
        }
      })
    },
    
    // 清空播放列表
    async clearPlaylist() {
      try {
        const result = await deviceApi.controlDevice(this.deviceId, {
          action: 'clearPlaylist'
        })
        
        if (result && result.errCode === 0) {
          this.playlist.patterns = []
          this.playlist.current_index = 0
          uni.showToast({
            title: '播放列表已清空',
            icon: 'success'
          })
        } else {
          uni.showToast({
            title: result?.errMsg || '清空播放列表失败',
            icon: 'none'
          })
        }
      } catch (error) {
        console.error('清空播放列表失败:', error)
        uni.showToast({
          title: '网络错误，请重试',
          icon: 'none'
        })
      }
    },
    
    // 从播放列表移除图案
    async removePattern(patternId) {
      if (!patternId) return
      
      try {
        const result = await deviceApi.controlDevice(this.deviceId, {
          action: 'removePattern',
          patternId: patternId
        })
        
        if (result && result.errCode === 0) {
          // 更新本地列表
          const index = this.playlist.patterns.findIndex(p => p.pattern_id === patternId)
          if (index !== -1) {
            this.playlist.patterns.splice(index, 1)
            
            // 调整当前播放位置
            if (index < this.playlist.current_index) {
              this.playlist.current_index--
            } else if (index === this.playlist.current_index && this.playlist.patterns.length > 0) {
              // 当前播放项被删除，但列表还有其他项
              this.playlist.current_index = Math.min(this.playlist.current_index, this.playlist.patterns.length - 1)
            } else if (this.playlist.patterns.length === 0) {
              // 列表已清空
              this.playlist.current_index = 0
            }
          }
          
          uni.showToast({
            title: '移除成功',
            icon: 'success'
          })
        } else {
          uni.showToast({
            title: result?.errMsg || '移除失败',
            icon: 'none'
          })
        }
      } catch (error) {
        console.error('移除图案失败:', error)
        uni.showToast({
          title: '网络错误，请重试',
          icon: 'none'
        })
      }
    },
    
    // 拖拽开始
    dragStart(event, index) {
      this.draggedItem = this.playlist.patterns[index]
      this.draggedIndex = index
      event.target.style.opacity = '0.5'
    },
    
    // 拖拽结束
    dragEnd(event) {
      event.target.style.opacity = '1'
      this.draggedItem = null
      this.draggedIndex = -1
    },
    
    // 拖拽放置
    async drop(event, targetIndex) {
      if (this.draggedIndex === -1 || this.draggedIndex === targetIndex) return
      
      // 先在本地更新
      const item = this.playlist.patterns.splice(this.draggedIndex, 1)[0]
      this.playlist.patterns.splice(targetIndex, 0, item)
      
      // 调整当前播放位置
      if (this.draggedIndex === this.playlist.current_index) {
        // 当前播放项被移动
        this.playlist.current_index = targetIndex
      } else if (this.draggedIndex < this.playlist.current_index && targetIndex >= this.playlist.current_index) {
        // 当前播放项前面的项被移到后面，当前项索引减1
        this.playlist.current_index--
      } else if (this.draggedIndex > this.playlist.current_index && targetIndex <= this.playlist.current_index) {
        // 当前播放项后面的项被移到前面，当前项索引加1
        this.playlist.current_index++
      }
      
      // 发送到服务器
      try {
        const result = await deviceApi.controlDevice(this.deviceId, {
          action: 'reorderPatterns',
          patterns: this.playlist.patterns
        })
        
        if (!(result && result.errCode === 0)) {
          uni.showToast({
            title: result?.errMsg || '调整顺序失败',
            icon: 'none'
          })
          // 如果失败，重新加载列表
          await this.loadPlaylist()
        }
      } catch (error) {
        console.error('调整顺序失败:', error)
        uni.showToast({
          title: '网络错误，顺序可能未保存',
          icon: 'none'
        })
        // 如果失败，重新加载列表
        await this.loadPlaylist()
      }
    },
    
    // 根据图案分类获取图标
    getPatternIcon(category) {
      const icons = {
        'nature': 'fa-mountain',
        'animal': 'fa-paw',
        'landscape': 'fa-tree',
        'abstract': 'fa-star',
        'character': 'fa-user',
        'holiday': 'fa-gift',
        'water': 'fa-water',
        'other': 'fa-shapes'
      }
      
      return icons[category] || 'fa-image'
    },
    
    // 格式化持续时间
    formatDuration(duration) {
      if (!duration) return '0:00'
      
      const minutes = Math.floor(duration / 60)
      const seconds = Math.floor(duration % 60)
      return `${minutes}:${seconds.toString().padStart(2, '0')}`
    }
  }
}
</script>

<style scoped>
/* TailwindCSS 工具类样式 */
.bg-white { background-color: #ffffff; }
.bg-gray-100 { background-color: #f3f4f6; }
.bg-gray-200 { background-color: #e5e7eb; }
.bg-blue-50 { background-color: #eff6ff; }
.bg-blue-100 { background-color: #dbeafe; }
.bg-blue-500 { background-color: #3b82f6; }
.bg-green-500 { background-color: #10b981; }
.bg-red-500 { background-color: #ef4444; }
.bg-gray-300 { background-color: #d1d5db; }

.text-white { color: #ffffff; }
.text-gray-300 { color: #d1d5db; }
.text-gray-400 { color: #9ca3af; }
.text-gray-500 { color: #6b7280; }
.text-gray-600 { color: #4b5563; }
.text-gray-700 { color: #374151; }
.text-gray-900 { color: #111827; }
.text-blue-500 { color: #3b82f6; }
.text-blue-600 { color: #2563eb; }
.text-red-500 { color: #ef4444; }
.text-red-600 { color: #dc2626; }

.text-xs { font-size: 24rpx; }
.text-sm { font-size: 28rpx; }
.text-base { font-size: 32rpx; }
.text-xl { font-size: 40rpx; }
.text-3xl { font-size: 48rpx; }

.font-medium { font-weight: 500; }
.font-bold { font-weight: 700; }

.h-screen { height: 100vh; }
.h-2 { height: 16rpx; }
.h-10 { height: 80rpx; }
.h-12 { height: 96rpx; }
.h-24 { height: 192rpx; }
.h-64 { height: 512rpx; }
.w-2 { width: 16rpx; }
.w-6 { width: 48rpx; }
.w-10 { width: 80rpx; }
.w-12 { width: 96rpx; }
.w-24 { width: 192rpx; }
.w-full { width: 100%; }

.flex { display: flex; }
.flex-col { flex-direction: column; }
.flex-1 { flex: 1; }
.items-center { align-items: center; }
.justify-center { justify-content: center; }
.justify-between { justify-content: space-between; }
.space-x-2 > * + * { margin-left: 16rpx; }
.space-x-4 > * + * { margin-left: 32rpx; }
.space-y-3 > * + * { margin-top: 24rpx; }

.p-2 { padding: 16rpx; }
.p-3 { padding: 24rpx; }
.p-4 { padding: 32rpx; }
.p-6 { padding: 48rpx; }
.px-2 { padding-left: 16rpx; padding-right: 16rpx; }
.px-6 { padding-left: 48rpx; padding-right: 48rpx; }
.py-1 { padding-top: 8rpx; padding-bottom: 8rpx; }
.py-3 { padding-top: 24rpx; padding-bottom: 24rpx; }
.py-4 { padding-top: 32rpx; padding-bottom: 32rpx; }
.py-6 { padding-top: 48rpx; padding-bottom: 48rpx; }
.py-8 { padding-top: 64rpx; padding-bottom: 64rpx; }
.pt-12 { padding-top: 96rpx; }
.pb-4 { padding-bottom: 32rpx; }
.pl-1 { padding-left: 8rpx; }
.pl-2 { padding-left: 16rpx; }
.pr-1 { padding-right: 8rpx; }
.pr-2 { padding-right: 16rpx; }

.mt-1 { margin-top: 8rpx; }
.mt-2 { margin-top: 16rpx; }
.mt-4 { margin-top: 32rpx; }
.mr-1 { margin-right: 8rpx; }
.mr-3 { margin-right: 24rpx; }
.mr-4 { margin-right: 32rpx; }
.mb-3 { margin-bottom: 24rpx; }
.mb-4 { margin-bottom: 32rpx; }
.block { display: block; }

.border { border-width: 2rpx; }
.border-b { border-bottom-width: 2rpx; }
.border-gray-100 { border-color: #f3f4f6; }
.border-blue-100 { border-color: #dbeafe; }

.rounded-lg { border-radius: 16rpx; }
.rounded-xl { border-radius: 24rpx; }
.rounded-full { border-radius: 50%; }

.overflow-auto { overflow: auto; }
.cursor-move { cursor: move; }

/* 额外的悬停样式 */
.hover-text-gray-600:active { color: #4b5563; }
.hover-text-gray-800:active { color: #1f2937; }
.hover-text-red-600:active { color: #dc2626; }

/* Font Awesome 图标样式 */
.fas {
  font-family: "Font Awesome 5 Free", "Font Awesome 5 Brands";
  font-weight: 900;
}
.fa-chevron-left:before { content: "\f053"; }
.fa-times:before { content: "\f00d"; }
.fa-music:before { content: "\f001"; }
.fa-play:before { content: "\f04b"; }
.fa-trash-alt:before { content: "\f2ed"; }
.fa-random:before { content: "\f074"; }
.fa-redo-alt:before { content: "\f2f9"; }
.fa-grip-vertical:before { content: "\f58e"; }
.fa-mountain:before { content: "\f6fc"; }
.fa-water:before { content: "\f773"; }
.fa-tree:before { content: "\f1bb"; }
.fa-paw:before { content: "\f1b0"; }
.fa-star:before { content: "\f005"; }
.fa-user:before { content: "\f007"; }
.fa-gift:before { content: "\f06b"; }
.fa-shapes:before { content: "\f61f"; }
.fa-image:before { content: "\f03e"; }

/* 加载动画 */
.loading-spinner {
  width: 40rpx;
  height: 40rpx;
  border: 4rpx solid rgba(59, 130, 246, 0.3);
  border-radius: 50%;
  border-top-color: #3b82f6;
  animation: spin 1s linear infinite;
}

@keyframes spin {
  0% { transform: rotate(0deg); }
  100% { transform: rotate(360deg); }
}

/* 播放列表项目样式 */
.playlist-item {
  transition: all 0.2s ease;
}

.playlist-item:active {
  transform: scale(0.98);
}
</style>
